package leetcode.tree;

import java.util.LinkedList;

/**
 * @author wangmaolin1
 * @date 2023/11/11 13:23
 */
public class _297 {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serialize0(root, sb);
        return sb.toString();
    }

    public void serialize0(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append("#,");
            return;
        }
        sb.append(root.val).append(",");
        serialize0(root.left,sb);
        serialize0(root.right,sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] split = data.split(",");
        LinkedList<String> list = new LinkedList<>();
        for (String s : split) {
            list.offer(s);
        }
        return deserialize0(list);
    }

    public TreeNode deserialize0(LinkedList<String> list) {
        if (list.isEmpty()) {
            return null;
        }
        String s = list.removeFirst();
        if ("#".equals(s)) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(s));
        root.left = deserialize0(list);
        root.right = deserialize0(list);
        return root;
    }

}
